<?php

namespace app\admin\controller;

use app\common\controller\Backend;

use think\Request;
use fast\lucn\Lucn;

/**
 * 黄花菜专题管理
 *
 * @icon fa fa-circle-o
 */
class Hhc extends Backend
{
    
    protected $model = null;
    protected $relationSearch = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Hhc');
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax())
        {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with("category")
                    ->where($where)
                    ->order($sort, $order)
                    ->count();
            $list = $this->model
                    ->with("category")
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }
	 
	protected function change($content){
		$arrimg = Lucn::getImg($content,4,true);
		return implode(',',$arrimg); //已改为，分割 lucn30
	}
	 
	private function unload($content){
		$arr_img = Lucn::getImg($content);
		$arr_img2 = array_unique($arr_img);
		foreach($arr_img2 as $i => $son){
			if(preg_match("/^(https|http):\/\/\S+/", $son)){//如果是远程图片
				$dir = 'uploads/hhc/unload/';
				$arr_fileinfo = Lucn::getImage($son,$dir);
				if($arr_fileinfo['error'] == 0){
					$content  = str_replace ($son,'/'.$dir.$arr_fileinfo['file_name'],$content);
				}
			}
		}
		return $content;
	}
	
	private function edit_data($params,$has_field)
	{
	    if ($has_field == 1)
                {
                    //JSON字段
                    $fieldarr = $valuearr = [];
                    $field = $this->request->post('field/a');
                    $value = $this->request->post('value/a');
                    foreach ($field as $k => $v)
                    {
                        if ($v != '')
                        {
                            $fieldarr[] = $field[$k];
                            $valuearr[] = $value[$k];
                        }
                    }
                    //$params['configure'] = array_combine($fieldarr, $valuearr);
                }
				//转存图片
				if(isset($params['getImage'])){
				  if($params['getImage'] == 'on'){
					$params['content'] = $this->unload($params['content']);
				  }
			    }
				//提取文中图片到图片组
				if(isset($params['content_thumb']) == true){
					if($params['content_thumb'] == 'on'){
					  $params['images'] = $this->change($params['content']);
					  //第一张图片写进image表
					  $arr_img = explode(',',$params['images']);
				      if(count($arr_img)>0 && empty($params['image']) == true){
				        $params['image'] = $arr_img[0];
				      }
					}
			    }
				//处理flag
				//$params['flag'] = isset($params['flag']) ? implode(',',$params['flag']) : '';
				unset($params['getImage']);
				unset($params['content_thumb']);
				
		 return $params;
				
	}
	/*
	public function add()
    {
        if ($this->request->isPost())
        {
            $this->code = -1;
            $params = $this->request->post("row/a");
            if ($params)
            {
                if ($this->request->has('field')){
				    $has_field = 1;
				}else{
				    $has_field = 0;
				}
                $params = $this->edit_data($params,$has_field);
                $this->model->save($params);
                $this->code = 1;
            }

            return;
        }
        return $this->view->fetch(Request::instance()->controller().'/edit');
    }
	*/
	
	/**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                foreach ($params as $k => &$v)
                {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
					$has_field = 0;
                    $params = $this->edit_data($params,$has_field);
                    $result = $this->model->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($this->model->getError());
                    }
                }
                catch (\think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch(Request::instance()->controller().'/edit');
    }
	
	/**
     * 编辑
     */
	public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $params = $this->request->post("row/a");
            if ($params)
            {
                foreach ($params as $k => &$v)
                {
                    $v = is_array($v) ? implode(',', $v) : $v;
                }
                try
                {
                    //是否采用模型验证
                    if ($this->modelValidate)
                    {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
					$has_field = 0;
                    $params = $this->edit_data($params,$has_field);
                    $result = $row->save($params);
                    if ($result !== false)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error($row->getError());
                    }
                }
                catch (think\exception\PDOException $e)
                {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }
/*	
	public function edit($ids = NULL)
    {
	    $row = $this->model->get(['id' => $ids]);
        if (!$row)
            $this->error(__('No Results were found'));
        if ($this->request->isPost())
        {
            $this->code = -1;
            $params = $this->request->post("row/a");
            if ($params)
            {
				$has_field = 0;
                $params = $this->edit_data($params,$has_field);
                $row->save($params);
                $this->code = 1;
            }

            return;
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
	}
*/    

}
